let activeEffect = null;

class Dep {
  constructor() {
    this.subscribers = new Set();
  }

  depend() {
    if (activeEffect) {
      this.subscribers.add(activeEffect);
    }
  }

  notify() {
    this.subscribers.forEach(effect => effect());
  }
}

function effect(eff) {
  activeEffect = eff;
  activeEffect();
  activeEffect = null;
}

function reactive(target) {
  const handler = {
    get(target, key, receiver) {
      const dep = getDep(target, key);
      dep.depend();
      return Reflect.get(target, key, receiver);
    },
    set(target, key, value, receiver) {
      const dep = getDep(target, key);
      const result = Reflect.set(target, key, value, receiver);
      dep.notify();
      return result;
    }
  };
  return new Proxy(target, handler);
}

const targetToDepMap = new WeakMap();
function getDep(target, key) {
  let depsMap = targetToDepMap.get(target);
  if (!depsMap) {
    depsMap = new Map();
    targetToDepMap.set(target, depsMap);
  }

  let dep = depsMap.get(key);
  if (!dep) {
    dep = new Dep();
    depsMap.set(key, dep);
  }
  return dep;
}

// 使用示例
const state = reactive({ count: 0 });

effect(() => {
  console.log(state.count);
});

state.count++;
